<template>
  <div class="ad">
      <div class="ad-title">用户</div>
      <span class="ad-button" @click ="handleFile">导入用户表</span>
      <span class="ad-button" @click="handleInsert">新增用户</span>
      <span class="ad-button" @click="handleDelete">删除用户</span>
      <span class="ad-button" @click="handleCandidate">选择为投票人</span>
      <span class="ad-button" @click="handleSaveUser">导出用户表</span>
      <div class="table">
         <tr>
              <th class="table-item">用户ID</th>
              <th class="table-item">用户名</th>
              <th class="table-item">密码</th>
              <th class="table-item">编辑</th>
              <th class="table-item delete">选择</th>
         </tr>
         <tr v-for="(item, index) in List" :key="item.vId" ref="index">
            <th class="table-item">{{item.vId}}</th>
            <th class="table-item">{{item.vName}}</th>
            <th class="table-item">{{item.vPassword}}</th>
            <th class="table-item alter" @click="handleAlter(item,index)">修改用户信息</th>
            <th class="table-item delete" :key="item.vId">
                <input type="checkbox" value="checked"
                v-model="select[index]"
                @click="handleSelectClick(index)"
                :ref="index">
            </th>
        </tr>
      </div>
  </div>
</template>

<script>
import axios from 'axios'
import { mapState } from 'Vuex'
export default {
  name: 'admin',
  props: {
    List: Array
  },
  data () {
    return {
      select: [],
      delete: []
    }
  },
  methods: {
    handleInsert () {
      this.$emit('insert')
    },
    handleFile () {
      this.$emit('file')
    },
    handleAlter (item, index) {
      this.$emit('alter', item, index)
      // console.log(item, index)
    },
    handleSelectClick (index) {
      this.select[index] = !this.select[index] === true
      if (this.select[index]) {
        this.$refs.index[index].style.background = '#41E1D1'
        //event.target.checked = true
        this.$refs[index][0].checked = true // 动态的改变复选框的选中状态
      } else {
        this.$refs.index[index].style.background = '#fff'
        //event.target.checked = false
        this.$refs[index][0].checked = false
      }
    },
    handleDelete () {
      if (!this.select.length) {
        swal('亲，您还没有选中数据呢！', '', 'error')
      } else {
        const verify = confirm('亲，您是否确定删除这(些)用户呢！请慎重考虑')
        if (verify) {
          // console.log(this.select)
          this.select.forEach((value, index) => {
            if (value) {
              this.delete.push(this.List[index])
              // console.log(this.delete)
            }
          })
          const arr = JSON.stringify(this.delete)
          axios.post('http://192.168.43.188:8081/deleteVoter', {
            'id': this.userId,
            arr
          })
            .then(({status, data}) => {
              if (status === 200) { // 这几行代码不能换成三等号
                // console.log(data)
                this.removeItem()
                // console.log(this.delete)
                if (data.msg[0] == '111') { // eslint-disable-line
                  swal('删除成功', '', 'success')
                } else if (data.msg[0] == '000') { // eslint-disable-line
                  swal('找不到该用户名', '', 'error')
                } else if (data.msg == '110') { // eslint-disable-line
                  swal('管理员id错误', '', 'error')
                } else if (data.msg == '010') { // eslint-disable-line
                  swal('该用户名的密码错误', '', 'error')
                }
              }
            }).catch((error) => {
              swal('Info' + error, '', 'error')
            })
        }
      }
    },
    removeItem () {
      this.delete.forEach(() => { // 保证循环次数
        this.select.forEach((value, index) => {
          if (value) {
            this.$emit('handleDelete')
            // console.log(this.List[index])
            this.List.splice(index, 1)
            this.select.splice(index, 1)
          }
        })
      })
      this.delete = []
    },
    handleCandidate () {
      if (!this.select.length) {
        swal('亲，您还没有选择投票人呢！', '', 'error')
      } else {
        const verify = confirm('亲，您是否选择这些用户为此次投票的投票人呢？')
        if (verify) {
          // console.log(this.select)
          this.select.forEach((value, index) => {
            if (value) {
              this.delete.push(this.List[index])
              // console.log(this.delete)
            }
          })
          const arr = []
          this.delete.forEach((item, index) => {
            arr[index] = item.vId
          })
          // console.log(arr)
          axios.post('http://192.168.43.188:8081/selectVoters', {
            'id': this.userId,
            arr
          })
            .then(({status, data}) => {
              if (status === 200) { // 这几行代码不能换成三等号
                console.log(data)
                this.handleColor()
                if (data.msg[0] == '111') { // eslint-disable-line
                  swal('选择投票人成功', '', 'success')
                  this.delete = []
                } else if (data.msg[0] == '000') { // eslint-disable-line
                  swal('找不到该用户名', '', 'error')
                } else if (data.msg == '110') { // eslint-disable-line
                  swal('管理员id错误', '', 'error')
                } else if (data.msg == '010') { // eslint-disable-line
                  swal('该用户名的密码错误', '', 'error')
                }
              }
            }).catch((error) => {
              swal('问题' + error, '', 'error')
            })
        }
      }
    },
    handleColor () {
      this.select.forEach((item, index) => {
        // console.log(index)
        this.handleSelectClick(index)
        // this.handleSelectClick(index)
      })
    },
    getAdminInfo () {
      // console.log(this.userId)
      // console.log(this.curPage.toString())
      axios.post('http://192.168.43.188:8081/getVCPages', {
        'id': this.userId,
        'pn': this.curPage.toString(),
        'jd': '0'
      }).then(({status, data}) => {
        // console.log(data)
        if (data && data.msg === '111') {
          this.totalPages = data.tp.toString()
          this.totalData = data.td.toString()
          this.list = data.info
        } else if (data.msg) {
          swal(data.msg, '', 'error')
        }
      }).catch((error) => {
        swal(error, '', 'error')
      })
    },
    handleSaveUser () {
      axios.post('http://192.168.43.188:8081/excelVoter', {
        'mid': this.userId
      }).then(({data, status}) => {
        if (status === 200) {
          this.handlePrintUser(data.url)
        } else {
          swal(data.msg, '', 'wraning')
        }
      }).catch((error) => {
        swal('Info' + error, '', 'error')
      })
    },
    handlePrintUser (url) {
      // console.log(url)
      const name = url.split('//')
      const fileName = name[name.length - 1]
      for (let i = 0; i < 2; i++) {
        axios({
          method: 'post',
          url: 'http://192.168.43.188:8081/download',
          responseType: 'blob',
          dataType: "jsonp",
          data: {'url': url},
         
        }).then(({data}) => {
          console.log('请求已发送')
          swal('请等待片刻', '', 'info')
          this.download(data, fileName)
          swal('download success', '', 'success')
        })
      } 
    },
    download (data, fileName) {
      if (!data) {
        swal('没有数据', '', 'info')
        return
      }
      let url = window.URL.createObjectURL(new Blob([data]))
      let link = document.createElement('a')
      // link.style.display = 'none'
      link.href = url
      link.setAttribute('download', fileName + '.xls')
      document.body.appendChild(link)
      link.click()
    }
  },
  computed: {
    ...mapState(['userId'])
  }
}
</script>

<style lang="stylus" scoped>
@import '~style/variable.styl'
.ad
    margin-top: .2rem
    text-align: center
    padding: 0 .5rem
    .ad-title
        background: $bgcolor
        color: #fff
        line-height: $height
        text-align: center
        margin-bottom: .5rem
    .ad-button
        overflow: hidden
        // display: block
        background: $bgcolor
        font-size: .32rem
        padding: .2rem .4rem
        margin: .2rem
        border-radius: .1rem
    .table
        margin-top: .5rem
        width: 100%
        .table-item
            border: .02rem solid #aaa
            width: 7rem
            // width: 23.95% /* 设置百分比失效 */
            height: .5rem
            line-height: .5rem
            padding: .2rem .0rem
        .alter
            color: $bgcolor
        .delete
            width: 3.2rem
</style>
